package com.wjn.basic.java8.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * java8 List<String> 类型的排序
 */
public class SortDemo {

    // 使用 java 7 排序
    private void sortUsingJava7(List<String> names){
        Collections.sort(names, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                return s1.compareTo(s2);
            }
        });
    }

    // 使用 java 8 排序
    private void sortUsingJava8(List<String> names){
        Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
    }

    // 非string类型的排序
    private void sortList(){
        List<User> list=new ArrayList<>();
        list.add(new User("1"));
        list.add(new User("2"));
        list.add(new User("5"));
        list.add(new User("4"));
        //排序lamda
        Comparator<User> comparator = Comparator.comparing(User::getUserName);
        Collections.sort(list, comparator);

        for (User user:list){
            System.out.println(user.getUserName());
        }

    }


    //User类
    class User{
        String username;

        public User(String username){
            this.username=username;
        }
        public String getUserName(){
            return username;
        }
    }

    public static void main(String[] args) {
        List<String> names1 = new ArrayList<String>();
        names1.add("Google ");
        names1.add("Runoob ");
        names1.add("Taobao ");
        names1.add("Baidu ");
        names1.add("Sina ");

        List<String> names2 = new ArrayList<String>();
        names2.add("Google ");
        names2.add("Runoob ");
        names2.add("Taobao ");
        names2.add("Baidu ");
        names2.add("Sina ");

        System.out.println("使用 Java 7 语法: ");
        SortDemo sortDemo=new SortDemo();
        sortDemo.sortUsingJava7(names1);
        System.out.println(names1);
        System.out.println("使用 Java 8 语法: ");

        sortDemo.sortUsingJava8(names2);
        System.out.println(names2);

        sortDemo.sortList();


    }




}
